<?php
/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-09-20
 * 版    本：1.0.0
 * 功能说明：后台首页控制器。
 *
 **/

namespace Gii\Controller;

use Think\Controller;

class CurdGeneratorController extends Controller
{
    public function _empty(){
        //把所有城市的操作解析到city方法
                return 404;
            }

    public function index()
    {

        //自动验证规则

        $this->display();

    }


    public function generator()
    {

        $data=array();
        $data['modelClass'] = I("modelClass");//模型类
        $data['searchModelClass'] = I("searchModelClass");//搜索查询模型类
        $data['controllerClass'] = I("controllerClass");//控制器类
        $data['viewPath'] = I("viewPath");//生成的页面路径
        $data['baseControllerClass'] = I("baseControllerClass");//基础类库
        $data['tablename'] = I("tablename"); //页面模板
        $view=$data['viewPath'];
        /*----------------模型名称以及控制器名称---------------------*/
        $model= trim($data['modelClass'])."Model.class.php";
        $controller= trim($data['controllerClass'])."Controller.class.php";
        //生成模型类文件
        /*-----------------------获取类名以及命名空间-----------------------------*/
        $modelName=$this->getName($data['modelClass']);  //模型名称
        $modelSpace=$this->getNameSpace($data['modelClass'], $modelName); //模型命名空间
        $controllerName=$this->getName($data['controllerClass']); //控制器名称
        $controllerSpace=$this->getNameSpace($data['controllerClass'], $controllerName); //控制器命名空间
        /*----------查询表的相关信息--------*/
        $modelTable=D($modelName);
        $listtable=$modelTable->query("desc ".$data['tablename'] );
        $arr2 = array_column($listtable, 'field'); //表头元素
        $arr3 = array_column($listtable, 'key'); //主键
        $pri=array_search("PRI",$arr3);
        $header="";
        $body="";
        $input=" ";
        $mod="";
        foreach ($arr2 as $key=>$vo)
        {
            $header.='<th>'.$vo.'</th>'."\n\r";
            $body.= '<td>{$vo["'.$vo.'"]}</td>'."\n\r";
            if($key!=$pri){
                $temp['name']=$vo;
                $tempdata['value']= '{$list["'.$vo.'"]}';
                $tempdata['name']=$vo;
                $input.= $this->tepleteReplace("input.html",$temp)."\n\r";
                $mod.= $this->tepleteReplace("mody.html",$tempdata)."\n\r";
            }else{

                $modData['prikey']=$vo;
                $modData['privalue']= '{$list["'.$vo.'"]}';
            }

        }

        /*------------------生成控制器类-----------------------------*/
        $controllerFile=$this->checkAndCreat($controller);
        $controllerData['namespace']=$controllerSpace;
        $controllerData['name']=$controllerName."Controller";
        $controllerData['modelname']=$modelName;
        $controllerData['tablename']= $data['tablename'];
        $controllerData['prikey']=$modData['prikey'];
        $content=$this->tepleteReplace("controller.html", $controllerData);
        $result= file_put_contents($controllerFile, $content);
        if(!$result)
        {
            echo "控制器类生成失败，请检查输入的格式是否正确";
        }
        /*--------------------生成模型类-----------------------------------*/
        $_validate=  "['title', 'check', '参数错误啦！', 1, 'callback', 3, '参数']";
        $modelFile=$this->checkAndCreat($model);
        $controllerData['namespace']=$modelSpace;
        $controllerData['name']=$modelName."Model";
        $controllerData['modelname']=$modelName;
        $controllerData['tablename']= $data['tablename'];
        $controllerData['validate']= $_validate;
        $content=$this->tepleteReplace("model.html", $controllerData);
        $result= file_put_contents($modelFile, $content);
        if(!$result)
        {
            echo "模型类生成失败，请检查输入的格式是否正确";
        }
        /*--------------------生成视图文件CURD---------------------------------*/

        /*---列表页-*/
        $lists['header']=$header;
        $lists['body']=$body;
        $lists['prikey']=$modData['prikey'];
        $list=$view.'lists.html';
        $viewFile=$this->checkAndCreat($list);
        $content=$this->tepleteReplace("lists.html", $lists);
        $result= file_put_contents($viewFile, $content);
        if(!$result)
        {
            echo "list视图文件生成失败，请检查输入的格式是否正确";
        }
        /*------新增页------*/
        $inputData['input']=$input;
        $inputView=$view.'add.html';
        $viewFile=$this->checkAndCreat($inputView);
        $content=$this->tepleteReplace("add.html", $inputData);
        $result= file_put_contents($viewFile, $content);
        if(!$result)
        {
            echo "add视图文件生成失败，请检查输入的格式是否正确";
        }
        /*---修改页面-----*/
        $modData['input']=$mod;
        $inputView=$view.'modify.html';
        $viewFile=$this->checkAndCreat($inputView);
        $content=$this->tepleteReplace("modify.html", $modData);
        $result= file_put_contents($viewFile, $content);
        if(!$result)
        {
            echo "modify视图文件生成失败，请检查输入的格式是否正确";
        }

//        $this->display();
    }

    /**检查并且创建文件
     * @param $file
     * @return mixed|string
     */
    public function checkAndCreat($file)
    {
        $new=$this->formatPath($file);
        $dir=explode(DIRECTORY_SEPARATOR,$new);
        $exist="";
        foreach ($dir as $a)
        {
            if(end($dir)!=$a){
                if (!is_dir($exist.$a.DIRECTORY_SEPARATOR))
                {
                    mkdir($exist.$a.DIRECTORY_SEPARATOR);
                }
                $exist.=$a.DIRECTORY_SEPARATOR;
            }else{
                $newfile=fopen($new,'w');
            }

        }
      return $new;
    }

    public function  formatPath($file)
    {
        $root = getcwd();//获取根目录
        $apppath=trim(APP_PATH,".");//获取配置中的应用路径
        $apppath=trim($apppath,"/");
        $new = $root.DIRECTORY_SEPARATOR .$apppath.DIRECTORY_SEPARATOR. $file;
        $new=str_replace("/", DIRECTORY_SEPARATOR, $new);
        $new=str_replace('\\', DIRECTORY_SEPARATOR, $new);
        return $new;
    }

    public  function  sysFormat($file)
    {
            $file=str_replace("/", DIRECTORY_SEPARATOR, $file);
            $file=str_replace('\\', DIRECTORY_SEPARATOR, $file);
            return $file;

    }
    public  function  getName($file)
    {
        $file= $this->sysFormat($file);
        $file=explode(DIRECTORY_SEPARATOR,$file);
        $name=end($file);
        return trim($name);
    }
    public function getNameSpace($file,$name)
    {
       $namespace=trim(strstr($file, $name, true),DIRECTORY_SEPARATOR) ;
        return $namespace;
    }
    //返回当前文件的上一层目录
    public  function fileUpperPath()
    {
        $ROOT=dirname(__FILE__);
        $pos=strripos($ROOT,DIRECTORY_SEPARATOR);
        $dir=substr($ROOT, 0,$pos);
        return $dir;
    }

    /**获取模板内容
     * 模板路径必须置于当前文件的上层同级目录
     * @param $file
     * @return bool|string
     */
    public  function  getTempleteFile($file)
    {
        $config=C("templete");
        $dir=$this->fileUpperPath();
        $aim=$dir.DIRECTORY_SEPARATOR.$config.DIRECTORY_SEPARATOR.$file;
        $aim= $this->sysFormat($aim);
        $content=file_get_contents($aim);
        return $content;
    }

    /**替换模板内容
     * @param $file 模板文件
     * @param $data  要替换的内容
     * @return bool|mixed|string
     */
    public  function  tepleteReplace($file,$data)
    {
       $content= $this->getTempleteFile($file);
        if($data)
        {
            foreach ($data as $key=>$value)
            {
                $search="{{".$key."}}";
                $replace=$value;
                $content=str_replace($search, $replace, $content);
            }
        }
        return $content;
    }
}
